﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using Fuse8.ContentManagementFramework.SystemFacade.Utilities;
using Fuse8.DomainFramework.Common;

namespace Fuse8.ContentManagementFramework.Administration.Models
{
    [ModelBinder(typeof(CmsEntityMetaModelBinder))]
    public class CmsEntityMetaModel
    {        
        public object Value { get; set; }
        public bool IsRequired { get; set; }
        public string Name { get; set; }
        public string Label { get; set; }
        public string Type { get; set; }
        public string EditorName { get; set; }
        public object AdditionalValues { get; set; }
        public string MetaValuesProviderName { get; set; }
        public bool CanAddNew { get; set; }
    }

    public class CmsEntityMetaModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var entity = new CmsEntityMetaModel
                             {
                                 Type = controllerContext.HttpContext.Request.Form[bindingContext.ModelName + ".Type"],
                                 Name = controllerContext.HttpContext.Request.Form[bindingContext.ModelName + ".Name"],
                                 IsRequired = Convert.ToBoolean(controllerContext.HttpContext.Request.Form[bindingContext.ModelName + ".IsRequired"])
                             };
            
            Type type = Type.GetType(entity.Type);            
            var binder = ModelBinders.Binders.GetBinder(type);
            if (binder != null)
            {
                var binding = new ModelBindingContext()
                                  {
                                      ModelName = bindingContext.ModelName + ".Value",
                                      ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => entity.Value, type),
                                      ValueProvider = bindingContext.ValueProvider,
                                      ModelState = bindingContext.ModelState
                                  };
                binding.ModelMetadata.IsRequired = entity.IsRequired;
                entity.Value = binder.BindModel(controllerContext, binding);
            }

            return entity;
        }
    }

    public class CmsEntityMetaModelContainer
    {
        public IList<CmsEntityMetaModel> Metas { get; set; }
    }
}